<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '220px'" class="aside">
      <div class="logo">
        <h1 v-if="!isCollapse">金融信贷管理系统</h1>
        <h1 v-else>系统</h1>
      </div>
      <!-- 菜单 -->
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        background-color="#001529"
        text-color="#fff"
        active-text-color="#409EFF"
        :unique-opened="true"
        router
      >
        <!-- 一级菜单 -->
        <template v-for="(menu, index) in menuList" :key="menu.path + '-' + index">
          <!-- 无子菜单且未隐藏 -->
          <el-menu-item 
            v-if="(!menu.children || menu.children.length === 0) && !menu.hidden" 
            :index="menu.path"
          >
            <el-icon><component :is="menu.icon || 'Document'" /></el-icon>
            <template #title>{{ menu.title }}</template>
          </el-menu-item>
          
          <!-- 有子菜单且未隐藏 -->
          <el-sub-menu 
            v-else-if="menu.children && menu.children.length > 0 && !menu.hidden" 
            :index="menu.path"
          >
            <template #title>
              <el-icon><component :is="menu.icon || 'Folder'" /></el-icon>
              <span>{{ menu.title }}</span>
            </template>
            
            <!-- 二级菜单 -->
            <template v-for="(subMenu, subIndex) in menu.children.filter(item => !item.hidden)" :key="subMenu.path + '-' + subIndex">
              <!-- 无子菜单的二级菜单 -->
              <el-menu-item 
                v-if="!subMenu.children || subMenu.children.length === 0" 
                :index="subMenu.path"
              >
                <el-icon v-if="subMenu.icon"><component :is="subMenu.icon" /></el-icon>
                <template #title>{{ subMenu.title }}</template>
              </el-menu-item>
              
              <!-- 有子菜单的二级菜单 -->
              <el-sub-menu 
                v-else 
                :index="subMenu.path"
              >
                <template #title>
                  <el-icon v-if="subMenu.icon"><component :is="subMenu.icon" /></el-icon>
                  <span>{{ subMenu.title }}</span>
                </template>
                
                <!-- 三级菜单 -->
                <el-menu-item 
                  v-for="(item, itemIndex) in subMenu.children.filter(item => !item.hidden)"
                  :key="item.path + '-' + itemIndex"
                  :index="item.path"
                >
                  <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
                  <template #title>{{ item.title }}</template>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-sub-menu>
        </template>
      </el-menu>
    </el-aside>

    <el-container>
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <el-button type="text" @click="toggleCollapse">
            <el-icon :size="20">
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </el-button>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="route.meta.title">
              {{ route.meta.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <div class="user-role">
            <el-tag v-if="userInfo.roles && userInfo.roles.includes('admin')" type="danger">管理员</el-tag>
            <el-tag v-else-if="userInfo.roles && userInfo.roles.includes('auditor')" type="warning">审批员</el-tag>
            <el-tag v-else-if="userInfo.roles && userInfo.roles.includes('finance')" type="success">财务</el-tag>
            <el-tag v-else-if="userInfo.roles && userInfo.roles.includes('user')" type="info">普通用户</el-tag>
          </div>
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userInfo.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" />
              <span class="username">{{ userInfo.realName || userInfo.username || '用户' }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主要内容区 -->
      <el-main class="main">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Expand,
  Fold,
  House,
  CreditCard,
  Money,
  Setting,
  User,
  Warning,
  Document,
  PieChart,
  Connection,
  Folder
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { generateMenusByRole } from '@/config/menu'
import { getUserInfo as fetchUserInfo } from '@/api/user'
import { getMenusByRole2 } from '@/config/menu2'

const route = useRoute()
const router = useRouter()
const isCollapse = ref(false)
const menuList = ref([])
const userInfo = ref({})

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 切换菜单折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  // 保存折叠状态到本地存储
  localStorage.setItem('menuCollapsed', isCollapse.value ? 'true' : 'false')
}

// 获取用户信息和菜单
const getUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      router.push('/login')
      return
    }
    
    try {
      // 调用API获取用户信息
      const res = await fetchUserInfo()
      if (res && (res.code === 200 || res.code === "200") && res.data) {
        userInfo.value = res.data
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        
        // 使用menu.js中的函数根据用户角色生成菜单
        if (userInfo.value && userInfo.value.roles && userInfo.value.roles.length > 0) {
          // 默认使用第一个角色生成菜单，如果需要处理多角色可以在这里调整
          // const role = userInfo.value.roles[0]
          const userId = userInfo.value.userId
          console.log('role:', userInfo.value.userId)
          // menuList.value = generateMenusByRole(role)
          menuList.value = await getMenusByRole2(userId)
          console.log('menuList:', menuList.value)
        } else {
          // 没有角色权限时使用基础菜单
          menuList.value = generateMenusByRole('user')
          console.log('没有角色权限时使用基础菜单:')
        }
      } else {
        // 如果API返回错误，则尝试使用本地存储的信息
        const localUserInfo = localStorage.getItem('userInfo')
        if (localUserInfo) {
          userInfo.value = JSON.parse(localUserInfo)
          if (userInfo.value && userInfo.value.roles && userInfo.value.roles.length > 0) {
            const role = userInfo.value.roles[0]
            menuList.value = generateMenusByRole(role)
          } else {
            menuList.value = generateMenusByRole('user')
          }
        } else {
          ElMessage.error('获取用户信息失败')
          router.push('/login')
          return
        }
      }
    } catch (error) {
      // API请求失败，尝试使用本地存储的用户信息
      const localUserInfo = localStorage.getItem('userInfo')
      if (localUserInfo) {
        userInfo.value = JSON.parse(localUserInfo)
        if (userInfo.value && userInfo.value.roles && userInfo.value.roles.length > 0) {
          const role = userInfo.value.roles[0]
          menuList.value = generateMenusByRole(role)
        } else {
          menuList.value = generateMenusByRole('user')
        }
      } else {
        ElMessage.error('获取用户信息失败')
        router.push('/login')
        return
      }
    }

    // 恢复菜单折叠状态
    const savedCollapsed = localStorage.getItem('menuCollapsed')
    if (savedCollapsed !== null) {
      isCollapse.value = savedCollapsed === 'true'
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败')
    router.push('/login')
  }
}

// 退出登录
const logout = async () => {
  try {
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('routesAdded')
    
    ElMessage.success('退出成功')
    router.push('/login')
  } catch (error) {
    console.error('退出失败', error)
    ElMessage.error('退出失败')
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    logout()
  } else if (command === 'profile') {
    router.push('/account/profile')
  } else if (command === 'password') {
    // 显示修改密码对话框
    router.push('/account/profile')
  }
}

// 组件挂载时获取用户信息和菜单
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.aside {
  background-color: #001529;
  transition: width 0.3s;
  overflow: hidden;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  color: #fff;
  font-size: 16px;
  background-color: #002140;
  overflow: hidden;
  white-space: nowrap;
}

.logo h1 {
  margin: 0;
  font-size: 18px;
  transition: all 0.3s;
}

.el-menu-vertical {
  border-right: none;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 220px;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left .el-button {
  margin-right: 15px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-role {
  margin-right: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  font-size: 14px;
}

.main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}

/* 优化菜单过渡效果 */
.el-menu-item, .el-sub-menu {
  transition: all 0.2s ease-out !important;
}

/* 使用硬件加速 */
.el-menu, .el-menu-item, .el-sub-menu {
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000px;
}
</style> 